import { AxiosBaseConfig } from "./model";
import { Dialog } from "antd-mobile";

// 默认错误消息映射
export const defaultErrorMessage = {
  400: "请求错误",
  401: "未授权，请重新登录",
  403: "拒绝访问",
  404: "请求地址出错",
  408: "请求超时",
  500: "服务器内部错误",
  501: "服务未实现",
  502: "网关错误",
  503: "服务不可用",
  504: "网关超时",
  505: "HTTP版本不受支持",
  default: "网络连接异常",
};

// 默认配置
let axiosBaseConfig: AxiosBaseConfig = {
  baseURL: "",
  timeout: 10000,
  useDefaultErrorHandler: true,
  successNetworkCode: 0,
  authInvalidCode: 401,
  authTokenName: "Authorization",
  messageName: "message",
  dataName: "data",
  authFailed: () => {
    Dialog.alert({
      content: "登录已失效，请重新登录",
      onConfirm: () => {
        localStorage.clear();
        if (window.ReactNativeWebView) {
          window.ReactNativeWebView.postMessage(
            JSON.stringify({
              messageId: "all.exit_login",
              data: "",
            })
          );
        } else {
          localStorage.clear();
          window.location.reload();
        }
      },
    });
  },
};

export const setAxiosBaseConfig = (config: AxiosBaseConfig) => {
  axiosBaseConfig = {
    ...axiosBaseConfig,
    ...config,
  };
};
export const getAxiosBaseConfig = () => {
  return axiosBaseConfig;
};
